package main.java.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
/*
 	ajax发送post请求访问servlet会出现跨域问题 (协议、域名、端口三者任意一个不同即为跨域)
 	这个过滤器用来解决跨域问题		
 */
public class CrosFilter implements Filter{
	
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("CrosFilter已创建");
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("进入过滤器CrosFilter");
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); //前端不会报错
		chain.doFilter(request, response);
		System.out.println("过滤器CrosFilter放行");
	}

	public void destroy() {
		System.out.println("CrosFilter已销毁");
	}
}
